<?php
/**
 * Created by PhpStorm.
 * User: luoshuqi
 * Date: 19-2-15
 * Time: 下午4:36
 */

namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use App\Models\SysUser;
use Illuminate\Http\Request;

class SysUserController extends Controller
{
    /**
     * @operation(管理员, 查看, 9000)
     * @return array
     */
    public function get()
    {
        $query = SysUser::query();
        $username = $this->filter('username');
        $username and $query->where('username', 'LIKE', "%$username%");

        $total = $query->count();

        $fields = ['id', 'username', 'group_id', 'enabled', 'created_at'];
        $list = $query->select($fields)->with('group:id,name')
            ->orderByDesc('id')
            ->forPage(...$this->page())
            ->get();

        return $this->ok(['total' => $total, 'list' => $list]);
    }

    /**
     * @operation(管理员, 创建)
     * @param Request $request
     * @return array
     * @throws \Illuminate\Validation\ValidationException
     */
    public function create(Request $request)
    {
        $params = $this->required($request, 'username', 'password', 'group_id', 'enabled');

        if (SysUser::query()->where('username', $params['username'])->exists()) {
            return $this->error('用户名已存在');
        }
        SysUser::query()->forceCreate($params);
        return $this->ok();
    }

    /**
     * @operation(管理员, 更新)
     * @param $id
     * @return array
     */
    public function find($id)
    {
        $fields = ['id', 'username', 'group_id', 'enabled', 'created_at'];
        $user = SysUser::query()->select($fields)->findOrFail($id);
        return $this->ok($user->toArray());
    }

    /**
     * @operation(管理员, 更新)
     * @param Request $request
     * @param $id
     * @return array
     * @throws \Illuminate\Validation\ValidationException
     */
    public function update(Request $request, $id)
    {
        $params = $this->required($request, 'username', 'group_id', 'enabled');
        $user = SysUser::query()->findOrFail($id);
        if ($user['username'] !== $params['username']) {
            if (SysUser::query()->where('username', $params['username'])->exists()) {
                return $this->error('用户名已存在');
            }
        }
        $user->forceFill($params);
        $user->save();
        return $this->ok();
    }


    /**
     * @operation(管理员, 删除)
     * @param $ids
     * @return array
     */
    public function delete($ids)
    {
        $ids = explode(',', $ids);
        SysUser::deleteById(...$ids);
        return $this->ok();
    }
}